@tool
extends Node2D

@onready var tileMap: TileMap = $'../TileMap'

# @export var start: Vector2i
# @export var end: Vector2i
# @export var caculate: bool

var astarGrid = AStarGrid2D.new()
var path := []

var size: int

func _ready():
	size = tileMap.rendering_quadrant_size
	pathCost()

# func _physics_process(_delta):
# 	if caculate:
# 		caculate = false
# 		pathCost()
# 		findWay(start, end)

func find(start: Vector2i, end: Vector2i):
	path = astarGrid.get_point_path(start, end)
	var i = 0

	while i < len(path):
		path[i] += Vector2(size / 2, size / 2)
		i += 1

	queue_redraw()
	return path

# 计算地图路径花费的时间
func pathCost():
	astarGrid.region = Rect2i( - tileMap.width, -tileMap.height, 2 * tileMap.width, 2 * tileMap.height)
	astarGrid.cell_size = Vector2(size, size)
	astarGrid.update()

	for x in range( - tileMap.width, tileMap.width):
		for y in range( - tileMap.height, tileMap.height):
			var coords = Vector2i(x, y)
			var time = getTime(coords)
			if time == - 1: astarGrid.set_point_solid(coords)
			else: astarGrid.set_point_weight_scale(coords, time)

# 获取走过此坐标所需时间
func getTime(coords: Vector2i):
	var layer = 0
	var sourceId = tileMap.get_cell_source_id(layer, coords)
	var source: TileSetAtlasSource = tileMap.tile_set.get_source(sourceId)
	var atlasCoords = tileMap.get_cell_atlas_coords(layer, coords)
	var tile = source.get_tile_data(atlasCoords, 0)

	return tile.get_custom_data('cost')

# 覆写绘制函数
func _draw():
	if len(path) > 0:
		for i in range(len(path) - 1):
			draw_line(path[i], path[i + 1], Color.YELLOW)
